class LoginController < ApplicationController
  before_filter :authorize, :except => :login
  layout "admin"

  def index
    @total_orders = Order.count
    @pending_orders = Order.count_pending
  end


  def add_user
    if request.get?
      @user = User.new
    else
      @user = User.new(params[:user])
      if @user.save
        redirect_to_index("用户 #{@user.name} 被创建。")
      end
    end
  end

  def login
    if request.get?
      session[:user_id] = nil
      @user = User.new
    else
      @user = User.new(params[:user])
      logged_in_user = @user.try_to_login
      if logged_in_user
        session[:user_id] = logged_in_user.id
        redirect_to(:action => "index")
      else
        flash[:notice] = "用户名或密码错误！"
      end
    end
  end

  #  def login
  #    session[:user_id] = nil
  #    if request.post?
  #      user = User.authenticate(params[:name], params[:password])
  #      if user
  #        session[:user_id] = user.id
  #        redirect_to(:action => "index")
  #      else
  #        flash[:notice] = "Invalid user/password combination"
  #      end
  #    end
  #  end


  def delete_user
    id = params[:id]
    if id && user = User.find(id)
      begin
        user.destroy
        flash[:notice] = "用户 #{user.name} 被删除。" rescue
        flash[:notice] = "不能删除该用户。"
      end
    end
    redirect_to(:action => :list_users)
  end

  def list_users
    @all_users = User.find(:all)
  end


  def logout
    session[:user_id] = nil
    flash[:notice] = "已经退出。"
    redirect_to(:action => "login")
  end


end
